/*
 * @Author: 千锋爱佛僧
 * @公众号: 大前端私房菜
 * @Slogan: 千锋精品教程，好学得不像实力派！
 */
import React, { Key, useEffect, useState } from "react";
import { Button, Checkbox, Form, Input, Tree } from "antd";
import { adminRoutes } from "@/router";
import { CheckedKeyType, RoleType } from "@/types/user";
import { rolePost, rolePut } from "@/api/user";

const onFinishFailed = (errorInfo: any) => {
  console.log("Failed:", errorInfo);
};
interface IRoleProps {
  initData: RoleType | null;
  idx: number;
  handleRoleList: (role: RoleType, index: number) => void;
}
const RoleForm = (props: IRoleProps) => {
  let [form] = Form.useForm();
  let [checkedKeys, setCheckedKeys] = useState<CheckedKeyType>([]);
  console.log("角色表单", props);

  const handleCheck = (checkedArr: CheckedKeyType) => {
    console.log(checkedArr);
    setCheckedKeys(checkedArr);
  };
  const onFinish = (values: RoleType) => {
    values.checkedKeys = checkedKeys;
    console.log("Success:", values);
    if (props.initData) {
      //修改
      rolePut(props.initData.objectId, values).then((res) => {
        props.handleRoleList({ ...props.initData, ...values }, props.idx);
      });
    } else {
      //新增
      rolePost(values).then((res) => {
        let { objectId } = res.data;
        props.handleRoleList({ ...values, objectId }, props.idx);
      });
    }
  };
  useEffect(() => {
    if (props.initData) {
      let { roleName, checkedKeys } = props.initData;
      form.setFieldsValue({ roleName });
      setCheckedKeys(checkedKeys);
    } else {
      form.resetFields();
      setCheckedKeys([]);
    }
  }, [props.initData]);
  return (
    <Form
      name="basic"
      form={form}
      labelCol={{ span: 8 }}
      wrapperCol={{ span: 16 }}
      style={{ maxWidth: 600 }}
      initialValues={{ remember: true }}
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
      autoComplete="off"
    >
      <Form.Item
        label="角色名称"
        name="roleName"
        rules={[{ required: true, message: "请输入角色" }]}
      >
        <Input />
      </Form.Item>

      <Form.Item
        label="菜单权限"
        name="checkedKeys"
        // rules={[{ required: true, message: "Please input your password!" }]}
      >
        <Tree
          treeData={adminRoutes}
          fieldNames={{ title: "label" }}
          checkable
          checkedKeys={checkedKeys}
          onCheck={handleCheck}
        />
      </Form.Item>

      <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
        <Button type="primary" htmlType="submit">
          {props.initData ? "修改" : "新增"}
        </Button>
      </Form.Item>
    </Form>
  );
};

export default RoleForm;
